<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 2018/11/9
 * Time: 13:25
 */

namespace Lesson\Controller;
use Common\Controller\HomebaseController;
use Order\Model\OrderModel;
use Professor\Model\ProfessorModel;
use Wx\Controller\WxPayController;

class LessonController extends HomebaseController {

    // 主页
    public function lesson_subject_index()
    {
        $lesson_subjects = M('lesson_subject')->order('sort desc')->limit(0)->select();
        $this->assign('lesson_subjects', $lesson_subjects);

        $profess_lists  = M('professor')
            ->alias('p')
            ->join('__USERS__ u on u.id = p.user_id', 'left')
            ->where(['p.advisory' => 1])
            ->order('p.advisory_sort desc')
            ->field('p.*, u.avatar, u.signature, u.user_nicename')
            ->limit(9)
            ->select();
        $this->assign('profess_lists', $profess_lists);
        $this->display();
    }

    // 主题主页
    public function lesson_list()
    {
        $subject_id     = I('subject_id');
        $subject_info   = M('lesson_subject')->where(['id' => $subject_id])->find();
        if ($subject_info['subject_price'] > 0) {
            if (sp_is_user_login()) {
                $has_buy = $this->is_user_buy_lesson($subject_id);
            } else {
                $has_buy = -1;
            }
        } else {
            $has_buy = 1;
        }

        // 用户是否登录并且有oa_openid
        $get_base_info = false;
        $user = sp_get_current_user();
        if ($user && !$user['oa_openid']) {
            $get_base_info = true;
        }
        $this->assign('get_base_info', $get_base_info);

        // 判断用户是否登录
        if (sp_is_user_login()) {
            $this->assign('is_login', 1);
            $this->assign('user', $user);
        } else {
            // 设置跳转url
            session('login_http_referer', U('Lesson/Lesson/lesson_list', ['subject_id' => $subject_id]));
            $this->assign('is_login', 0);
        }

        $lesson_lists = M('lesson')
            ->alias('l')
            ->join("__USERS__ u on u.id = l.lecturer_user_id", 'left')
            ->where(['l.subject_id' => $subject_id])
            ->order('l.sort desc')
            ->field('l.*, u.user_nicename, u.avatar')
            ->limit(0)
            ->select();
        $this->assign('subject_info', $subject_info);
        $this->assign('lists', $lesson_lists);
        $this->assign('has_buy', $has_buy);
        $this->display();
    }

    // 课程详情页
    public function lesson_index()
    {
        $this->check_login();
        $id = I('id');
        if ($id) {
            $lesson = M('lesson')
                ->alias('l')
                ->join("__USERS__ u on u.id = l.lecturer_user_id", 'left')
                ->where(['l.id' => $id])
                ->field('l.*, u.user_nicename, u.avatar, u.company, u.position, (select GROUP_CONCAT(name) FROM rx_label where FIND_IN_SET(id, l.labels) order by id) as label_names')
                ->find();
            // 专题信息
            $subject_info = M('lesson_subject')->where(['id' => $lesson['subject_id']])->find();
            if ($lesson && $subject_info) {
                $has_buy        = $this->is_user_buy_lesson($lesson['subject_id']); // 是否已购买
                $is_professor   = M('professor')->where(['user_id' => sp_get_current_userid(), 'del_time' => 0, 'status' => ProfessorModel::PF_STATUS_NORMAL])->find(); // 是否主讲人自己
                if ($is_professor || $has_buy || $subject_info['subject_price'] <= 0 || $lesson['free'] > 0) {
                    if ($lesson) {
                        if (!empty($lesson['labels'])) {
                            $lesson['label_names'] = array_filter(explode(',', $lesson['label_names']));
                        } else {
                            $lesson['label_names'] = [];
                        }
                        // 附近文稿
                        $lesson_file = json_decode($lesson['lesson_file'], true);
                        $lesson['lesson_file_path']     = $lesson_file['lesson_file_path'];
                        $lesson['lesson_file_name']     = $lesson_file['lesson_file_name'];

                        // 专题信息
                        $subject_info = M('lesson_subject')->where(['id' => $lesson['subject_id']])->find();
                        $this->assign('subject_info', $subject_info);

                        // 课程视频信息
                        $lesson_video_info = M('video')->where(['id' => $lesson['lesson_video_id']])->find();
                        $playInfo   = get_video_play_info($lesson_video_info['video_id']);

                        $this->assign('PlayURL', $playInfo[0]->PlayURL);
                        $lesson['video_type'] = $lesson_video_info['video_type'];

                        // 本专题课程列表
                        $lesson_lists = M('lesson')->where(['subject_id' => $lesson['subject_id']])->order('sort desc')->limit(0)->select();
                        $this->assign('lesson_lists', $lesson_lists);

                        $this->assign('lesson', $lesson);
                        $this->display();
                    } else {
                        $this->error('这节课溜走了~');
                    }
                } else {
                    $this->error('该课程为付费课程，请先购买~');
                }
            } else {
                $this->error('这节课溜走了~');
            }
        } else {
            $this->error('这节课溜走了~');
        }
    }

    // 课程购买
    public function lesson_buy()
    {
        $user_id    = I('user_id', 0);
        $user_info  = sp_get_current_user();
        if (!$user_info) {
            $user_info = M('users')->where(['id' => $user_id])->find();
            if (!$user_info) {
                $this->error('请先登录', U('User/Login/index', ['redirect' => base64_encode($_SERVER['REQUEST_URI'])]));exit;
            }
        }
        $subject_id     = I('subject_id', 0, 'intval');
        $pay_type       = I('get.pay_type');
        $subject_info   = M('lesson_subject')->where(['id' => $subject_id])->find();
        if ($subject_id && $subject_info) {

            $order_model    = D('Order/Order');
            $pay_type       = $pay_type ?: OrderModel::ORDER_PAY_TYPE_WX_NATIVE;

            // 检查是否支付过了
            $can_buy = $order_model->checkTicketLimit($user_info['id'], OrderModel::ORDER_TYPE_LESSON, $subject_id, 1);
            if ($can_buy) {

                // 支付总额
                $total_fee  = $subject_info['subject_price'] * 100;

                // 检查是否有重复订单
                $notBuy = $order_model->CheckOldOrder($user_info['id'], OrderModel::ORDER_TYPE_LESSON, $subject_id, $total_fee, 0, true);
                if (array_key_exists('trade_order_id', $notBuy)) {
                    // 可以沿用之前的订单
                    $order_id           = $notBuy['order_id'];
                    $trade_order_id     = $notBuy['trade_order_id'];
                } else {
                    $new_order  = $order_model->CreateOrder($user_info['id'], OrderModel::ORDER_TYPE_LESSON, $subject_id, 1, $total_fee);
                    if ($new_order['status'] == 1) {
                        $order_id       = $new_order['order_id'];
                        $trade_order_id = $new_order['trade_order_id'];
                    } else {
                        $this->error('操作失败，请稍后再试');
                        exit;
                    }
                }

                $attach = $pay_type;
                if ($order_id) {
                    if ($pay_type == OrderModel::ORDER_PAY_TYPE_WX_NATIVE) {
                        // 微信支付--native 扫码支付
                        $wx = new WxPayController();
                        $wx->send_native_pay_request("课程培训", $attach, $trade_order_id, $total_fee, $subject_id);

                    } elseif ($pay_type == OrderModel::ORDER_PAY_TYPE_WX_H5) {
                        // 微信支付--H5 扫码支付
                        $wx         = new WxPayController();
                        $redirect   = 'http://' . C('DOMAIN_NAME') . '/index.php?g=Lesson&m=Lesson&a=lesson_list&subject_id='.$subject_id;
                        $pay_url    = $wx->send_h5_pay_request("课程培训", $attach, $trade_order_id, $total_fee, $redirect);
                        $data       = array('status' => 1, 'pay_url' => $pay_url);
                        $this->ajaxReturn($data);

                    } elseif ($pay_type == OrderModel::ORDER_PAY_TYPE_WX_JSAPI) {
                        // 微信支付--JASPI 公众号内调起微信支付
                        $wx = new WxPayController();
                        if (empty($user_info['oa_openid'])) {
                            session('user', null);
                            $this->error('请用微信重新登录', U('User/Login/index', ['redirect' => base64_encode($_SERVER['REQUEST_URI'])]));
                        } else {
                            $parameters  = $wx->getJsapiPayParameters("课程培训", $attach, $trade_order_id, $total_fee, $subject_id, $user_info['oa_openid']);
                            $this->assign('subject_id', $subject_id);
                            $this->assign('parameters', $parameters);
                            $this->display();exit;
                        }
                    } elseif ($pay_type == OrderModel::ORDER_PAY_TYPE_WX_MINI) {
                        // 微信支付--微信支付--小程序内支付
                        $wx = new WxPayController();
                        if (empty($user_info['mn_openid'])) {
                            session('user', null);
                            session('login_http_referer', U('Lesson/Lesson/lesson_list', ['subject_id' => $subject_id]));
                            $this->ajaxReturn(['msg' => '请先登录', 'status' => -2]);
                        } else {
                            $parameters = $wx->getMiniPayParameters("课程培训", $attach, $trade_order_id, $total_fee, $subject_id, $user_info['mn_openid']);
                            $this->ajaxReturn([
                                'status'        => 1,
                                'parameters'    => $parameters,
                                'back_url'      => get_current_http_type() . $_SERVER["SERVER_NAME"] . U('Lesson/Lesson/lesson_list', ['subject_id' => $subject_id])
                            ]);
                        }
                    } else {
                        $this->error('请选择正确的支付方式');
                    }
                }
            } else {
                $this->redirect(U('Lesson/Lesson/lesson_list', ['subject_id' => $subject_id]));
            }
        } else {
            $this->error('这个课程溜走了。。');
        }
    }

    private function is_user_buy_lesson($lesson_subject_id = 0) {
        $user_id = sp_get_current_userid();
        // 直接购买
        $has_buy = M('order')
            ->where(['user_id' => $user_id, 'goods_id' => $lesson_subject_id, 'type' => OrderModel::ORDER_TYPE_LESSON, 'status' => OrderModel::ORDER_STATUS_HAS_PAY])
            ->find();
        if ($has_buy) {
            return 1;
        } else {
            return -1;
        }
    }
}

